package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 密码比对
        // 后期需要进行md5加密，然后再进行比对
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!md5.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        // 补齐要保存的对象的数据  最终要保存的对象是Employee
        // 1.把DTO中已有的属性都设置到Employye中，再补齐缺失的
        Employee employee = new Employee();
        // 属性拷贝，可以把指定对象的属性拷贝到另一个目标对象中。前提：属性名及数据类型要对应
        BeanUtils.copyProperties(employeeDTO, employee);
        // 补齐
        // 2. 密码要加密处理，同时使用常量类中的默认密码
        employee.setPassword(
                DigestUtils.md5DigestAsHex(
                        PasswordConstant.DEFAULT_PASSWORD
                                .getBytes(StandardCharsets.UTF_8)));
        // 3. 状态默认为启用
        employee.setStatus(StatusConstant.ENABLE);
        /*// 4.创建和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 5. 需要获取当前登录的用户id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/

        // 6. 调用mapper，完成保存功能
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        // 调用PageHelper设置分页参数
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        // 调用mapper进行查询
        Page<Employee> page = employeeMapper.findByName(employeePageQueryDTO.getName());

        // 构造PageResult
        PageResult pageResult = new PageResult();
        pageResult.setRecords(page.getResult());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    @Override
    public void enableOrDisable(Employee employee) {
        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        return employeeMapper.getById(id);
    }

    @Override
    public void edit(EmployeeDTO employeeDTO) {
        // 1.把DTO中已有的属性都设置到Employye中，再补齐缺失的
        Employee employee = new Employee();
        // 属性拷贝，可以把指定对象的属性拷贝到另一个目标对象中。前提：属性名及数据类型要对应
        BeanUtils.copyProperties(employeeDTO, employee);
        // // 创建和修改时间
        // employee.setUpdateTime(LocalDateTime.now());
        // // 需要获取当前登录的用户id
        // employee.setUpdateUser(BaseContext.getCurrentId());

        // 调用mapper的修改功能
        employeeMapper.update(employee);
    }

}
